import store from '@/store';

/**
 * Store工具函数集合
 */

// 获取用户信息
export const getUserInfo = () => {
  return store.getters['user/userInfo'];
};

// 获取用户ID
export const getUserId = () => {
  return store.getters['user/userId'];
};

// 获取token
export const getToken = () => {
  return store.getters['user/token'];
};

// 检查是否登录
export const isLogin = () => {
  return store.getters['user/isLoggedIn'];
};

// 检查是否为分销商
export const isDistributor = () => {
  return store.getters['user/isDistributor'];
};

// 检查权限
export const hasPermission = (permission) => {
  return store.getters['user/hasPermission'](permission);
};

// 检查角色
export const hasRole = (role) => {
  return store.getters['user/hasRole'](role);
};

// 用户登录
export const login = (loginData) => {
  return store.dispatch('user/login', loginData);
};

// 用户登出
export const logout = () => {
  return store.dispatch('user/logout');
};

// 获取商品列表
export const getGoodsList = (params) => {
  return store.dispatch('goods/getGoodsList', params);
};

// 获取订单列表
export const getOrderList = (params) => {
  return store.dispatch('order/getOrderList', params);
};

// 获取分销商信息
export const getDistributorInfo = () => {
  return store.dispatch('distribution/getDistributorInfo');
};

// 成为分销商
export const becomeDistributor = () => {
  return store.dispatch('distribution/becomeDistributor');
};

// 获取佣金列表
export const getCommissionList = (params) => {
  return store.dispatch('distribution/getCommissionList', params);
};

// 获取团队信息
export const getTeamMembers = (params) => {
  return store.dispatch('distribution/getTeamMembers', params);
};

// 显示加载状态
export const showLoading = (title = '加载中...') => {
  uni.showLoading({ title });
  store.dispatch('setLoading', true);
};

// 隐藏加载状态
export const hideLoading = () => {
  uni.hideLoading();
  store.dispatch('setLoading', false);
};

// 显示提示信息
export const showToast = (title, icon = 'none') => {
  uni.showToast({ title, icon });
};

// 显示确认框
export const showModal = (options) => {
  return new Promise((resolve) => {
    uni.showModal({
      ...options,
      success: (res) => {
        if (res.confirm) {
          resolve(true);
        } else {
          resolve(false);
        }
      }
    });
  });
};

// 页面跳转（需要登录）
export const navigateToWithAuth = (url) => {
  if (!isLogin()) {
    showModal({
      title: '提示',
      content: '请先登录',
      showCancel: false
    }).then(() => {
      // 跳转到登录页面
      uni.navigateTo({
        url: '/pages/login/login'
      });
    });
    return false;
  }
  
  uni.navigateTo({ url });
  return true;
};

// 页面跳转（分销商专属）
export const navigateToForDistributor = (url) => {
  if (!isDistributor()) {
    showModal({
      title: '提示',
      content: '您还不是分销商，是否立即成为分销商？',
      confirmText: '立即成为',
      cancelText: '暂不'
    }).then((confirm) => {
      if (confirm) {
        becomeDistributor();
      }
    });
    return false;
  }
  
  uni.navigateTo({ url });
  return true;
};

// 格式化金额
export const formatMoney = (amount) => {
  if (!amount && amount !== 0) return '0.00';
  return parseFloat(amount).toFixed(2);
};

// 格式化时间
export const formatTime = (timestamp, format = 'YYYY-MM-DD HH:mm:ss') => {
  if (!timestamp) return '';
  
  const date = new Date(timestamp);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hour = String(date.getHours()).padStart(2, '0');
  const minute = String(date.getMinutes()).padStart(2, '0');
  const second = String(date.getSeconds()).padStart(2, '0');
  
  return format
    .replace('YYYY', year)
    .replace('MM', month)
    .replace('DD', day)
    .replace('HH', hour)
    .replace('mm', minute)
    .replace('ss', second);
};

// 复制到剪贴板
export const copyToClipboard = (text) => {
  return new Promise((resolve, reject) => {
    uni.setClipboardData({
      data: text,
      success: () => {
        showToast('已复制到剪贴板');
        resolve();
      },
      fail: reject
    });
  });
};

// 保存图片到相册
export const saveImageToAlbum = (url) => {
  return new Promise((resolve, reject) => {
    uni.downloadFile({
      url,
      success: (res) => {
        uni.saveImageToPhotosAlbum({
          filePath: res.tempFilePath,
          success: () => {
            showToast('保存成功');
            resolve();
          },
          fail: reject
        });
      },
      fail: reject
    });
  });
};

// 分享功能
export const shareToFriends = (options) => {
  return new Promise((resolve, reject) => {
    uni.share({
      provider: 'weixin',
      scene: 'WXSceneSession',
      type: 0,
      ...options,
      success: resolve,
      fail: reject
    });
  });
};

// 分享到朋友圈
export const shareToMoments = (options) => {
  return new Promise((resolve, reject) => {
    uni.share({
      provider: 'weixin',
      scene: 'WXSceneTimeline',
      type: 0,
      ...options,
      success: resolve,
      fail: reject
    });
  });
};

// 生成二维码
export const generateQRCode = (text) => {
  // 这里可以调用后端API生成二维码
  // 或者使用第三方二维码生成库
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve('二维码生成结果');
    }, 1000);
  });
};

// 防抖函数
export const debounce = (func, wait) => {
  let timeout;
  return function executedFunction(...args) {
    const later = () => {
      clearTimeout(timeout);
      func(...args);
    };
    clearTimeout(timeout);
    timeout = setTimeout(later, wait);
  };
};

// 节流函数
export const throttle = (func, limit) => {
  let inThrottle;
  return function executedFunction(...args) {
    if (!inThrottle) {
      func(...args);
      inThrottle = true;
      setTimeout(() => inThrottle = false, limit);
    }
  };
};

// 深拷贝
export const deepClone = (obj) => {
  if (obj === null || typeof obj !== 'object') return obj;
  if (obj instanceof Date) return new Date(obj.getTime());
  if (obj instanceof Array) return obj.map(item => deepClone(item));
  if (typeof obj === 'object') {
    const clonedObj = {};
    for (const key in obj) {
      if (obj.hasOwnProperty(key)) {
        clonedObj[key] = deepClone(obj[key]);
      }
    }
    return clonedObj;
  }
};

// 生成唯一ID
export const generateUniqueId = () => {
  return Date.now().toString(36) + Math.random().toString(36).substr(2);
};